import OSS from 'ali-oss'

const myOss = {
  dataURLtoBlob: (dataurl) => {
    const arr = dataurl.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
  },
  // --上传图片到OSS并返回图片预览地址--
  ossUpload: (opts, dataurl) => {
    const client = new OSS({
      bucket: opts.bucket,
      region: opts.region,
      accessKeyId: opts.accessKeyId,
      accessKeySecret: opts.accessKeySecret
    })
    const forBlob = myOss.dataURLtoBlob(dataurl)
    const storeAs = opts.folder ? opts.folder + '/' + opts.fileName : opts.fileName
    async function put () {
      try {
        return client.put(storeAs, forBlob).then((result) => { return result })
      } catch (err) {
        return err
      }
    }
    return put()
  },
  // --判断OSS里图片是否存在--
  isThere: (opts, fileName) => {
    const client = new OSS({
      bucket: opts.bucket,
      region: opts.region,
      accessKeyId: opts.accessKeyId,
      accessKeySecret: opts.accessKeySecret
    })
    async function isExistObject (name, options = {}) {
      try {
        await client.head(name, options)
        return true
      } catch (err) {
        if (String(err.code) === 'NoSuchKey') return false
      }
    }
    return isExistObject(fileName)
  },
  // --删除OSS里的图片--
  ossDelete: (opts, fileName) => {
    const client = new OSS({
      bucket: opts.bucket,
      region: opts.region,
      accessKeyId: opts.accessKeyId,
      accessKeySecret: opts.accessKeySecret
    })
    async function deleteFile () {
      try {
        return await client.delete(fileName)
      } catch (err) {
        return err
      }
    }
    return deleteFile()
  }
}

export default myOss
